package de.lulusoft.anothertorrent.core.exceptions;

import java.net.SocketException;

import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClientException;
import org.apache.xmlrpc.client.XmlRpcHttpTransportException;
import org.xml.sax.SAXParseException;

import de.lulusoft.anothertorrent.core.xmlrpc.ConnectionManager;

/**
 * Provides static methods for handling/transforming Exceptions in this plugin.
 */
public class ExceptionHandler {
	
	public static final String ERROR_INFOHASH = "Could not find info-hash.";
	
	public static AnotherTorrentException convert(Throwable e)
	{
		if (e instanceof XmlRpcException) {
			if (e instanceof XmlRpcClientException)	{
				if (((XmlRpcClientException) e).linkedException instanceof SAXParseException) {
					return new XmlRpcParseException("Could not parse servers response.", e);
				}
			}
			else if (e instanceof XmlRpcHttpTransportException) {
				return new ServerNotConnectedException(e.getMessage(), e);
			}
			else if (e.getMessage().equals(ERROR_INFOHASH))
				return new RTorrentNoInfoHashException(e.getMessage(), e);
			else if (e.getMessage().equals((ConnectionManager.ERROR_NOT_CONNECTED)))
				return new ServerNotConnectedException(e.getMessage(), e);
		}
		else if (e instanceof SocketException) {
			return new ServerNotConnectedException(e.getMessage(), e);
		}
		
		return new UnknownException(e.getMessage(), e);
	}
}
